//index.js
//获取应用实例
//--引入整个项目的app.js文件，用来取其中的公共变量等信息--
const app = getApp();
var date = require('../util/date.js');
var util = require('../util/util.js');
Page({
  //--本页面的组建的内部数据,
  //--会渲染到该页面的wxml文件中,
  //--通过setData修改data数据，驱动页面渲染---
  data: {
    billTypeItems:[
      { name: 'yin', value: '1', target:'电银', checked: 'true' },
      { name: 'business', value: '2', target:'电商' }
    ],
    hidden: true,
    currentDate: '',
    expiringDate: '',
    days: 180,//计息天数
    changeDays: 0,//调整天数
    billType: "1",//类型
    billAmount: 0,//金额默认十万
    yearRate: 0,//年利率
    monthRate: 0,//月利率
    serviceCharge: 0,//手续费
    debit10: 0,//每十万扣款
    discountInterest: 0,//贴现利息
    discountAmount: 0,//贴现金额
    subNum: 0,//调整天数差
    id: 0,
    isUser: true
  },
  //类型修改
  billTypeChange:function(e){
    this.setData({
      billType: e.detail.value,
    })
  },
  //计算公式
  result: function(days,amount,rate,charge){
    //计算每十万扣款
    let x = 0;//每十万扣款
    let y = 0;//贴现利息
    let z = 0;//贴现金额

    //计算每十万扣款
    x = 10 * 10000 * rate * days / 360 + parseFloat(charge);
    y = x * (amount / 100000);
    z = amount - y;
    this.setData({
      debit10: util.comdify(util.dot(x)),//每十万扣款
      discountInterest: util.comdify(util.dot(y)),//贴现利息
      discountAmount: util.comdify(util.dot(z)) //贴现金额
    })
  },
  //贴现日期修改
  currentDateChange: function (e) {
    var cDate = date.formatDate(e.detail.value, 'yyyy-MM-dd');
    var eDate = date.formatDate(this.data.expiringDate, 'yyyy-MM-dd');
    let oldDate = this.data.currentDate;
    let a = new Date(cDate);
    let b = new Date(eDate);
    
    if (a>b){
      this.setData({
        currentDate: oldDate
      })
      wx.showToast({
        title: "贴现日期不能小于到期日期，请重新选择日期",
        icon: "none"
      })
      return
    }
    if (this.data.changeDays){
      //计息天数
      var oDays = util.getDayTime(cDate, eDate) + this.data.changeDays;
    }else{
      var oDays = util.getDayTime(cDate, eDate);
    }
    //console.info("贴现日期修改，贴现日期：" + cDate + "，到期日期：" + eDate+ "，计算计息天数："+oDays);
    
    //金额 以元为单位
    var amount = parseFloat(this.data.billAmount) * 10000;
    //年利率
    let rate = parseFloat(this.data.yearRate) / 100;
    //手续费
    let sCharge = parseFloat(this.data.serviceCharge);
    //赋值
    this.setData({
      currentDate: cDate,
      days: oDays
    })  
    //计算
    if (amount && rate){
      this.result(days, amount, rate, sCharge);
    }
  },
  //到期日期修改
  expiringDateChange: function (e) {
    var cDate = date.formatDate(this.data.currentDate, 'yyyy-MM-dd');
    var eDate = date.formatDate(e.detail.value, 'yyyy-MM-dd'); 
    let oldDate = this.data.expiringDate;
    let a = new Date(cDate);
    let b = new Date(eDate);
    if (a > b) {
      this.setData({
        expiringDate: oldDate
      })
      wx.showToast({
        title: "到期日期不能小于贴现日期，请重新选择日期",
        icon: "none"
      })
      return
    }
    //计息天数
    if (this.data.changeDays) {
      var oDays = util.getDayTime(cDate, eDate) + this.data.changeDays;
    } else {
      var oDays = util.getDayTime(cDate, eDate);
    }
    //console.info("到期日期修改，贴现日期：" + cDate + "，到期日期：" + eDate + "，计算计息天数：" + oDays);
    //金额 以元为单位
    var amount = parseFloat(this.data.billAmount) * 10000;
    //年利率
    let rate = parseFloat(this.data.yearRate) / 100;
    //手续费
    let sCharge = parseFloat(this.data.serviceCharge);
    //赋值
    this.setData({
      expiringDate: eDate,
      days: oDays
    }) 
    //获取结果
    if (amount && rate) {
      this.result(days, amount, rate, sCharge);
    }
  },
  //调整天数改变 调整 计息天数
  cDaysChange(e) {
    //如果输入的值
    let reg = /^-?[0-9]\d*$/;
    //输入的值
    let num0 = parseFloat(e.detail.value);
   // console.info("调整天数为===" + num0);
    //原本的调整天数值
    let num1 = parseFloat(this.data.changeDays);
    //两个值的先后差距
    let subNum = num0 - num1;
    //得到计息天数
    let days = this.data.days + subNum;
    //console.info("计息天数为===" + days);
    //赋值 调整天数 以及计息天数
    this.setData({
      changeDays: num0,
      subNum: subNum,
      days: days
    })
    //如果存在利率 计算每十万扣款
    let rate = parseFloat(this.data.yearRate) / 100;//利率
    let amount = parseFloat(this.data.billAmount) * 10000;//金额
    //手续费
    let sCharge = parseFloat(this.data.serviceCharge);
    //获取结果
    if (rate && amount) {
      this.result(days, amount, rate, sCharge);
    }
  },
  //金额修改
  amountChange(e) {
    //金额 以元为单位
    let amount = parseFloat(e.detail.value) * 10000;
    //console.info("金额===" + amount);
    this.setData({
      billAmount: parseFloat(e.detail.value),
    })
    //年利率
    let rate = parseFloat(this.data.yearRate) / 100;
    //天数
    let days = this.data.days;
    //手续费
    let sCharge = parseFloat(this.data.serviceCharge);
    //获取结果
    if (rate && amount) {
      this.result(days, amount, rate, sCharge);
    }
  },
  //年利率修改
  yRateChange(e) {
    let yRate = parseFloat(e.detail.value);
    if (yRate > 100) {
      yRate =100;
    } else if (yRate < 0) {
      yRate = 0;
    }
    //月利率
    let mRate = yRate / 100 / 12 * 1000;
    //console.info("年利率==" + yRate / 100 + " , 月利率==" + mRate);
    //赋值
    this.setData({
      yearRate: yRate,
      monthRate: util.dot(mRate),
    })
    //金额
    let amount = parseFloat(this.data.billAmount) * 10000;
    //天数
    let days = this.data.days;
    //年利率
    let rate = parseFloat(yRate) / 100;
    //手续费
    let sCharge = parseFloat(this.data.serviceCharge);
    //获取结果
    if (days && amount) {
      this.result(days, amount, rate, sCharge);
    }
  },
  //月利率修改
  mRateChange(e) {
    let mRate = parseFloat(e.detail.value);
    if (mRate > 100) {
      mRate = 100;
    } else if (mRate < 0) {
      mRate = 0;
    }
    //金额
    let amount = parseFloat(this.data.billAmount) * 10000;
    //年利率
    let yRate = mRate / 1000 * 12 * 100;
    //赋值
    this.setData({
      yearRate: util.dot(yRate),
      monthRate: mRate,
    })
    //利率
    let rate = parseFloat(yRate) / 100;
    //console.info("年利率==" + rate + " , 月利率==" + mRate);
    //天数
    let days = this.data.days;
    //手续费
    let sCharge = parseFloat(this.data.serviceCharge);
    //获取结果
    if (days && amount) {
      this.result(days, amount, rate, sCharge);
    }
  },
  //手续费修改
  sChargeChange:function(e){
    let sCharge = parseFloat(e.detail.value);
    //赋值
    this.setData({
      serviceCharge: sCharge
    })
    //金额
    let amount = parseFloat(this.data.billAmount) * 10000;
    //年利率
    let rate = parseFloat(this.data.yearRate) / 100;
    //天数
    let days = this.data.days;
    //获取结果
    if (days && amount && rate) {
      this.result(days, amount, rate, sCharge);
    }
  },
  //清空
  clearInput() {
    let date1 = date.formatDate(new Date(), 'yyyy-MM-dd');
    let date2 = util.handleDate(date1, 180);
    this.setData({
      currentDate: date1,
      expiringDate: date2,
      days: 180,
      changeDays: 0,//调整天数
      billType: "1",//类型
      billAmount: 0,//金额默认十万
      yearRate: 0,//年利率
      monthRate: 0,//月利率
      serviceCharge: 0,//手续费
      debit10: 0,//每十万扣款
      discountInterest: 0,//贴现利息
      discountAmount: 0,//贴现金额
      subNum: 0,//调整天数差
    })
  },
  //保存结果
  keepResult:function(){
    let that = this;
    let openId = (wx.getStorageSync('openId'));
    if (!openId){
      app.myWarn();
      return
    }
    let a = this.data;
    //计算结果里 三个数值会带有千分符 需要处理
    let mRate = a.monthRate || 0;
    let yRate = a.yearRate || 0;
    let bAmount = a.billAmount || 0;
    let data = {
      discountDate: a.currentDate,
      expirationDate: a.expiringDate,
      interestDay: a.days,
      daysRemaining: a.changeDays,//调整天数
      billType: a.billType,//类型
      billAmount: bAmount,//金额
      interestRateYear: yRate,//年利率
      monthlyInterestRate: mRate,//月利率
      serviceCharge: a.serviceCharge,//手续费
      debit10: util.comdifyback(a.debit10),//每十万扣款
      discountRate: util.comdifyback(a.discountInterest),//贴现利息
      discountAmount: util.comdifyback(a.discountAmount),//贴现金额
      userOpenid: openId
    }
    //console.info("保存的数据"+data)
    const url = app.globalData.api + "/wechat/calculation/save";
    wx.request({
      url: url,
      method: "POST",
      data: data,
      success: function (res) {
        //console.info(res);
        //失败的情况 返回值是什么
        if (res.data.code == 0) {
          //console.info("计算结果保存,数据ID==" + res.data.id);
          that.setData({
            id: res.data.id
          })
        }else{
          wx.showToast({
            title: "保存失败，请稍后重试",
            icon: "none"
          })
        }
      },fail(err){
        wx.showToast({
          title: "网络报错，请稍后重试！",
          icon: "none"
        })
      }
    })
  },
  //--生命周期函数onLoad()监听页面加载,
  //--onReady()页面初次渲染,
  //--onShow()页面显示,
  //--onHide()页面隐藏,
  //--onShareAppMessage()设置页面分享的信息
  onLoad: function (opt) {
    //初始化页面的时候，默认贴现日期是当日，到期日期是半年，调整天数为0，计息天数是180天
    //判断是否需要获取用户信息
    var openId = (wx.getStorageSync('openId'));
    // console.info("判断是否需要获取用户信息，是否显示button=" + !openId);
    if (!openId){
      //不存在user
      this.setData({
        isUser: true
      })
    }else{
      //存在user 可以不用显示按钮
      this.setData({
        isUser: false
      })
    }
    let date1 = date.formatDate(new Date(), 'yyyy-MM-dd');
    let date2 = util.handleDate(date1, 180);
    //console.info("默认到期日期，贴现日期：" + date1 + "，到期日期：" + date2 + "，计算计息天数：" + 180);
    this.setData({
      currentDate: date1,
      expiringDate: date2,
      days: 180,
      changeDays: 0,//调整天数
      billType: "1",//类型
      billAmount: 0,//金额默认十万
      yearRate: 0,//年利率
      monthRate: 0,//月利率
      serviceCharge: 0,//手续费
      debit10: 0,//每十万扣款
      discountInterest: 0,//贴现利息
      discountAmount: 0,//贴现金额
      subNum: 0,//调整天数差
    })
  },
  //获取用户信息
  getUserInfo: function(e) {
    let that = this
    // console.log(e)
    if (e.detail&&e.detail.userInfo){//存在userInfo
      that.setData({
        isUser: false
      })
      //调方法,设置缓存
      app.myLogin(e.detail.userInfo)
    }else{
      //不存在
      app.myWarn();
      that.setData({
        isUser: true
      })
    }
  },
  //点击分享
  toShare(e){
    this.keepResult();
    this.setData({
      hidden: false
    })
  },
  cancle() {
    this.setData({
      hidden: true
    })
  },
  //分享
  onShareAppMessage: function (options) {
    // console.log(options);
    var that = this;
    let id = this.data.id;
    var shareObj = {
      title: '实时计算器',
      path: '/pages/index/index',
      success: function (res) {
        that.cancle();
        console.info("转发成功")
      },
      fail: function (res) {
        console.info("取消转发");
      }
    };
    if (options.from == 'button') {
      //修改 shareObj 中的内容
      shareObj.title = '计算详情';
      //shareObj.path = '/pages/index/calcDetail/calcDetail?id=0&fromCalc=' + toDetail.fromCalc;
      shareObj.path = '/pages/index/calcDetail/calcDetail?id='+id;
    }
    return shareObj;
  },
  /**
 * 生命周期函数--监听页面显示
 */
  onShow: function (e) {
    //判断是否需要获取用户信息
    var openId = (wx.getStorageSync('openId'));
    //console.info("判断是否需要获取用户信息，是否显示button=" + !openId);
    if (!openId) {
      this.setData({
        isUser: true
      })
      return;
    } 
    this.setData({
      isUser: false
    })
    
    let calcList = app.globalData.calcParameters;
    //console.info(calcList);
    let date1 = date.formatDate(new Date(), 'yyyy-MM-dd');
    let date2 = date.formatDate(new Date(calcList.expiringDate), 'yyyy-MM-dd');
    if (calcList.isBillDetail || calcList.isCalcDetail) {
      this.setData({
        currentDate: date1,
        expiringDate: date2,
        days: calcList.days,//计息天数
        changeDays: calcList.changeDays,//调整天数
        billType: calcList.billType,//类型
        billAmount: calcList.billAmount,//金额默认十万
        yearRate: calcList.yearRate,//年利率
        monthRate: calcList.monthRate,//月利率
        serviceCharge: calcList.serviceCharge,//手续费
        debit10: calcList.debit10,//每十万扣款
        discountInterest: calcList.discountInterest,//贴现利息
        discountAmount: calcList.discountAmount,//贴现金额
        subNum: 0,//调整天数差
      })
    }else{
      this.clearInput();
    }
  },

})
